package com.greateffect.littlebud.lib.views;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

import com.greateffect.littlebud.lib.R;

/**
 * Created by ZengCS on 2019/8/14.
 * E-mail:zcs@sxw.cn
 * Add:成都市天府软件园E3-3F
 */
public class HorizontalProgressBar extends View {
    private Paint mPaint;
    private float mProgress;
    private static final int DFT_COLOR = 0xFFFD6F6E;

    private int mProgressColor;

    public HorizontalProgressBar(Context context) {
        this(context, null);
    }

    public HorizontalProgressBar(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public HorizontalProgressBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        TypedArray mTypedArray = context.obtainStyledAttributes(attrs, R.styleable.HorizontalProgressBar);
        mProgressColor = mTypedArray.getColor(R.styleable.HorizontalProgressBar_progressColor, DFT_COLOR);
        mTypedArray.recycle();

        init();
    }

    private float mWidth, strokeWidth;

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        strokeWidth = getMeasuredHeight();
        if (mPaint != null) {
            mPaint.setStrokeWidth(strokeWidth);
        }
    }

    private void init() {
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setStyle(Paint.Style.FILL);
        if (strokeWidth > 0)
            mPaint.setStrokeWidth(strokeWidth);
        mPaint.setColor(mProgressColor);
    }

    public void setProgress(float mProgress) {
        if (mWidth == 0)
            mWidth = getMeasuredWidth();
        this.mProgress = mProgress;
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawLine(0, strokeWidth/2, mWidth * mProgress / 100, strokeWidth/2, mPaint);
    }
}
